package classfile

/*
LineNumberTable_attribute {
    u2 attribute_name_index;
    u4 attribute_length;
    u2 line_number_table_length;
    {   u2 start_pc;
        u2 line_number;
    } line_number_table[line_number_table_length];
}
*/

type LineNumberTableEntry struct {
	startPC    uint16
	lineNumber uint16
}

type LineNumberTableAttribute struct {
	lineNumberTable []*LineNumberTableEntry
}

func (lnta *LineNumberTableAttribute) readInfo(reader *ClassReader) {
	lineNumberTableLen := reader.readUint16()
	lnt := make([]*LineNumberTableEntry, lineNumberTableLen)
	for i := range lnt {
		lnt[i] = &LineNumberTableEntry{
			startPC:    reader.readUint16(),
			lineNumber: reader.readUint16(),
		}
	}
	lnta.lineNumberTable = lnt
}

func (lnta *LineNumberTableAttribute) GetLineNumber(pc int) int {
	for i := len(lnta.lineNumberTable) - 1; i >= 0; i-- {
		entry := lnta.lineNumberTable[i]
		if pc >= int(entry.startPC) {
			return int(entry.lineNumber)
		}
	}
	return -1
}
